var _fparentid = "-1",IDName = "";
var fNumber,fName,fModel;
var jj;
var _fClosed=1;
/*
* @Description: 预加载
* @param :
*/
var index;
var field;
$(function(){
	$.fn.zTree.init($("#bomTree"), setting);
	initBomTable();
	for(index=1;index<7;index++){
		//ifTime(index);
		$('#field'+index).change(function(){
			field = $(this).val();
			console.log(field);
		})
	}
});
/*
* @Description: 模态框显示事件
* @param :
*/
$('#ERPModal').on('show.bs.modal', function () {
	fnResize();
});
/*
 * @Description: 模态框隐藏事件
 * @param :
 */
$('#ERPModal').on('hidden.bs.modal', function () {
	$.fn.zTree.init($("#bomTree"), setting);
	$('#fnumber,#fname,#fmodel').val("");
	_fparentid = "-1";
	initBomTable();
});

/*
* @Description: 树操作
* @param :
*/
var setting = {
	async : {
		enable : true,
		url : pathUrl("Bom/getAllBom.action"),
		type : "POST",
		dataFilter : filter
	},
	view : {
		dblClickExpand : false,
		selectedMulti : false,
		showIcon : false
	},
	edit : {
		enable : true,
		showRemoveBtn : false,
		showRenameBtn : false
	},
	data : {
		/*
		 * keep: { parent:true, leaf:true },
		 */
		simpleData : {
			enable : true,
		}
	},
	callback : {
		onClick : onClick,
		onAsyncSuccess : zTreeOnAsyncSuccess
	}
};

/*
* @Description: 对返回的json数据进行处理
* @param : treeId	对应zTree的treeId
* @param : parentNode	进行异步加载的父节点 JSON 数据对象
* @param : childNodes	异步加载获取到的数据
*/
function filter(treeId, parentNode, childNodes) {
	//	console.log(childNodes);
	if (!childNodes)
		return null;
	for ( var i = 0, l = childNodes.length; i < l; i++) {
		if (childNodes[i].pId == -1) {
			childNodes[i].open = "true";
		}
	}
	return childNodes;
}

/*
* @Description: 树异步加载正常结束的事件回调
* @param : event	js event对象
* @param : treeId	对应zTree的treeId
* @param : treeNode	被点击的节点JSON数据对象
* @param : msg	异步获取的节点数据字符串
*/
function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
//	swal.close();//关闭提示框
}

/*
* @Description: 点击节点事件
* @param : event	js event对象
* @param : treeId	对应zTree的treeId
* @param : treeNode	被点击的节点JSON数据对象
* @param : clickFlag	节点被单击后的选中类型
*/
function onClick(event, treeId, treeNode, clickFlag) {
//	console.log(treeNode);
	var _pId = treeNode.pId;
	var _name = treeNode.name;
	var children = treeNode.children;
	var zTree = $.fn.zTree.getZTreeObj("bomTree");
	
	if(children == undefined){
		_fparentid = treeNode.id;
//		$("#info").text(_name+"BOM信息");
	}else{
		_fparentid = "-1";
		zTree.expandNode(treeNode);
//		$("#info").text("BOM信息");
	}
	$('#fnumber,#fname,#fmodel').val("");
	initBomTable();
}
/*
* @Description: 初始化bom表 
* @param :
*/
function initBomTable() {
	$("#bom").bootstrapTable('destroy').bootstrapTable({
		url : pathUrl("Bom/getAllBomTree.action"),
		height: $(window).height() * 0.65 - 30,
		method : "POST",
		cache : false,
		sidePagination : "client", // 分页方式：client客户端分页，server服务端分页（*）
		queryParams : function(params) {
			var data = {},fnumber = $("#fnumber").val(), fname = $("#fname").val(),
			fmodel =  $("#fmodel").val();
			data.row = 10000000;
			data.fnumber = fnumber;
			data.fname = fname;
			data.fmodel = fmodel;
			if(fnumber == "" && fname == "" && fmodel == ""){
				data.fparentid = _fparentid;
			}
//			console.log(data)
			return data;
		},
		dataType : 'JSON',
		uniqueId : "",
		columns : [ {
			field : 'fNumber',
			align : 'left',
			title : '代码',
			edit : false
		}, {
			field : 'fName',
			align : 'left',
			title : '名称',
			edit : false
		},{
			field : 'FHelpCode',
			align : 'center',
			title : '助记码',
			formatter : attribute,
			edit : false
		},{
			field : 'fModel',
			align : 'left',
			title : '规格型号',
			edit : false
		}],
		onLoadSuccess:function(row, $element) {
		/*	var data=row;
			var index;
			var _fNumber=row.fNumber;
			var _fName=row.fName;
			var _fModel=row.fModel;
			for(index=1;index<7;index++){
				$('#field'+index).change(function(){
					var field = $(this).val();
					console.log(field);
					ifDoble(index,_fNumber,_fName,_fModel,field);
				})
			}*/
		},
		onClickRow : function(row, $element) {
//			console.log(row)
		},
		onDblClickRow : function(row, $element){
			var data=row;
			var index;
			var _fNumber=row.fNumber;
			var _fName=row.fName;
			var _fModel=row.fModel;
			/*for(index=1;index<7;index++){
				ifDoble(index,_fNumber,_fName,_fModel,field);
			}*/
			var field = $("#field"+jj).val();
			ifDoble(index,_fNumber,_fName,_fModel,field);
			$("#fNumber").val(row.fNumber);//物料代码
			$("#fName").val(row.fName);//物料名称
			$("#fModel").val(row.fModel);//规格型号
			$("#ERPModal").modal('hide');
		}
	});
}
/*
 * @Description: 重置按钮点击事件 
 * @param :
 */
$("#chongzhi").click(function() {
	$('#fnumber,#fname,#fmodel').val("");
	initBomTable();
});
/*
 * @Description: 浏览器窗口大小改变后：
 * 				 class为ztree，divClassLeft，divClassRight的高度随之改变，
 * 				 divClassLeft的最大高度和最小高度随之改变
 * @param :
 */
function fnResize() {
	var height = $(window).height() * 0.7;//获取浏览器窗口大小
//	console.log(height)
	$("#modal-body").height(height);
	$("#showDivClassRight").height(height - 10);
	document.getElementsByClassName("ztree")[0].style.height = (height - 15) +"px";
//	$(".fixed-table-container thead th .th-inner").attr('padding',0);
}


function ifDoble(index,_fNumber,_fName,_fModel,field){
	$("#valueBox"+index).html("");
	console.log(field);
	console.log(field=="fNumber");
	console.log(_fNumber);
	console.log(_fName);
	console.log(_fModel);
	if(field=="fNumber"){
		/*var h = "<input type='text' name='value"+index+"' id='value"+jj+"' value='"+_fNumber+"' class='form-control-new searchInput' autocomplete='off'>";
		$("#valueBox"+index).html(h);*/
		$("#value"+jj).val(_fNumber);
		
	}
	else  if(field=="fName"){
		/*var h = "<input type='text' name='value"+index+"' id='value"+jj+"' value='"+_fName+"' class='form-control-new searchInput' autocomplete='off'>";
		$("#valueBox"+index).html(h);*/
		$("#value"+jj).val(_fName);
	}
	else if(field=="fModel"){
		/*var h = "<input type='text' name='value"+index+"' id='value"+jj+"' value='"+_fModel+"' class='form-control-new searchInput' autocomplete='off'>";
		$("#valueBox"+index).html(h);*/
		$("#value"+jj).val(_fModel);
	}
	else{
		var h = "<input type='text' name='value"+index+"' id='value"+jj+"' value='' class='form-control-new searchInput' autocomplete='off'>";
	}
	
}
var colField;
var colFields;
var customColumn = [];
var customsubColumn= [];
var pageIds;
var PIESS;
var searchCount = 1;
var sqlCombine = "";
var lastRecordName = "";
var initTableName;
var fDisPatchFlag = null;
var fStatus = null;
var fClosed = null;
var fOrderBillNo=null;
/*
 *@Description: 自定义列按钮点击事件
 * @param :
 */
$("#changeColumn").click(function(){
	createCustomColumn();
	$("#changeColumnModal").modal("show");
});
$("#changeColumne").click(function(){
	createCustomColumns();
	$("#changeColumnModals").modal("show");
});
/*
 *@Description: 获取用户自定义的列
 * @param :
 */
function getColumn(pageId,funcName){	
	$.ajax({
		url : pathUrl("tz/getColumn.action"),
		type : "POST",
		dataType : "JSON",
		data : {
			'pageId':pageId			
		},
		success : function(data) {
			if (data.code == "0000") {
				if(data.rows.length == 0){//初始化为默认列						
					customColumn = cloneObjectFn(resetColumn);
				}else{//自定义列					
					createTableClumn(data.rows[0].columns);					
				}				
				funcName();
			} else if (data.code == "9999") {
				swal_Tips(data.message);
			}
		},
		error : function(request) {
			swal_Tips_Error();
		}
	});
}
/*
 *@Description: 获取用户自定义的列
 * @param :
 */
function getColumns(pageId,funcName){	
	$.ajax({
		url : pathUrl("tz/getColumn.action"),
		type : "POST",
		dataType : "JSON",
		data : {
			'pageId':pageId			
		},
		success : function(data) {
			if (data.code == "0000") {
				if(data.rows.length == 0){//初始化为默认列						
					customsubColumn = cloneObjectFn(resetsubColumn);
				}else{//自定义列					
					createTableClumns(data.rows[0].columns);					
				}				
				funcName();
			} else if (data.code == "9999") {
				swal_Tips(data.message);
			}
		},
		error : function(request) {
			swal_Tips_Error();
		}
	});
}
/**
 * @Description: 模态框显示
 * @param even
 * @returns
 */
function createTableClumn(col){
	var cols = new Array();
	cols = col.split(";");
	customColumn = cloneObjectFn(resetColumn);
	for(var i = 0; i < cols.length; i++){
		var temp = cols[i].split(",");
		var id = temp[1];
		for(var k = 0; k < customColumn.length; k++){
			if(customColumn[k].field != undefined && customColumn[k].field == id){
				if(temp[2] == "true"){
					customColumn[k].visible = true;	
				}else{
					customColumn[k].visible = false;
				}	
				customColumn[k].width = temp[3];
			}
		}
	}
}
/**
 * @Description: 模态框显示
 * @param even
 * @returns
 */
function createTableClumns(col){
	var cols = new Array();
	cols = col.split(";");
	customsubColumn = cloneObjectFn(resetsubColumn);
	for(var i = 0; i < cols.length; i++){
		var temp = cols[i].split(",");
		var id = temp[1];
		for(var k = 0; k < customsubColumn.length; k++){
			if(customsubColumn[k].field != undefined && customsubColumn[k].field == id){
				if(temp[2] == "true"){
					customsubColumn[k].visible = true;	
				}else{
					customsubColumn[k].visible = false;
				}	
				customsubColumn[k].width = temp[3];
			}
		}
	}
}
/**
 * @Description: 实现点击div也可以实现checkbox的勾选或者取消
 * @param even
 * @returns
 */
function changeState(even){	
	var id = even.getAttribute("id").substr(0,even.getAttribute("id").length - 3);//获取id	
	var f = $("#" + id + "Check")[0].checked;
	if(f == true){
		$("#" + id + "Check")[0].checked = false;
	}else{
		$("#" + id + "Check")[0].checked = true;
	}
}
/*
 * @Description: 封装自定的列
 * @param : 
 */
function createCustomColumn(){		
	$("#cusColumn").html("");
	var h = "";
	colField = [];
	for(var i = 0,j = 0; i < customColumn.length; i++){
		var s = customColumn[i];
		if(s.field != undefined && s.field != ""){
			if(s.must == true){
				h += "<div class='customColumn'><div class='inputClass'><input class='inputCheck' disabled = true style='float: left;' type='checkbox' checked = true ";
			}
			else if(s.hidden==true){
				h += "<div class='customColumn' style='display:none;'><div class='inputClass'><input class='inputCheck' disabled = true style='float: left; display:none;' type='checkbox' checked = true ";
			}
			else {
				h += "<div class='customColumn'><div class='inputClass'><input class='inputCheck' style='float: left;' type='checkbox' ";
				if(s.visible == true){
					h += "checked = true ";
				}
			}	
			var colTitle = formatTitle(s.title,"</br>");
			
			if(s.must == true){
				h += "id = '"+s.field+"Check' value='"+colTitle+"'/><div style='float: left;'>"+colTitle+"</div>";
				h += "<div style='float:right'><span>宽度</span><input style='inline-size: 39px;height: 17px;font-size: 15px;border: 0px;margin-left: 6px;' id='" + s.field +"Width' value='"+s.width.substr(0,s.width.length -1)+"'/>";
				h += "<span>%<span></div><div style='float:right'>（必选）</div></div></div>";
			}
			else if(s.hidden==true){
				h += "id = '"+s.field+"Check' value='"+colTitle+"'/><div style='float: left;'>"+colTitle+"</div>";
				h += "<div style='float:right;display:none;'><span>宽度</span><input style='inline-size: 39px;height: 17px;font-size: 15px;border: 0px;margin-left: 6px;' id='" + s.field +"Width' value='"+s.width.substr(0,s.width.length -1)+"'/>";
				h += "<span>%<span></div><div style='float:right;display:none;'>（必选）</div></div></div>";
			}
			else{
				h += "id = '"+s.field+"Check' value='"+colTitle+"'/><div style='width: 70%;float:left;' onclick='changeState(this)' id='" + s.field + "Div'>"+colTitle + "</div>";
				h += "<div style='float:right'><span>宽度</span><input style='inline-size: 39px;height: 17px;font-size: 15px;border: 0px;margin-left: 6px;' id='" + s.field +"Width' value = '" + s.width.substr(0,s.width.length -1) + "'/>";
				h += "<span>%<span></div></div></div>";
			}			
			colField[j] = s.field;
			j++;
		}
	}
	$("#cusColumn").html(h);	
}
/*
 * @Description: 封装自定的列
 * @param : 
 */
function createCustomColumns(){		
	$("#cusColumns").html("");
	var h = "";
	colFields = [];
	for(var i = 0,j = 0; i < customsubColumn.length; i++){
		var s = customsubColumn[i];
		if(s.field != undefined && s.field != ""){
			if(s.must == true){
				h += "<div class='customsubColumn' style='border: 1px solid #4e524e7d;'><div class='inputClass'><input class='inputCheck' disabled = true style='float: left;' type='checkbox' checked = true ";
			}
			else if(s.hidden==true){
				h += "<div class='customsubColumn' style='display:none;'><div class='inputClass'><input class='inputCheck' disabled = true style='float: left; display:none;' type='checkbox' checked = true ";
			}
			else {
				h += "<div class='customsubColumn' style='border: 1px solid #4e524e7d;'><div class='inputClass'><input class='inputCheck' style='float: left;' type='checkbox' ";
				if(s.visible == true){
					h += "checked = true ";
				}
			}	
			var colTitle = formatTitle(s.title,"</br>");
			
			if(s.must == true){
				h += "id = '"+s.field+"Check' value='"+colTitle+"'/><div style='float: left;'>"+colTitle+"</div>";
				h += "<div style='float:right'><span>宽度</span><input style='inline-size: 39px;height: 17px;font-size: 15px;border: 0px;margin-left: 6px;' id='" + s.field +"Width' value='"+s.width.substr(0,s.width.length -1)+"'/>";
				h += "<span><span></div><div style='float:right'>（必选）</div></div></div>";
			}
			else if(s.hidden==true){
				h += "id = '"+s.field+"Check' value='"+colTitle+"'/><div style='float: left;'>"+colTitle+"</div>";
				h += "<div style='float:right;display:none;'><span>宽度</span><input style='inline-size: 39px;height: 17px;font-size: 15px;border: 0px;margin-left: 6px;' id='" + s.field +"Width' value='"+s.width.substr(0,s.width.length -1)+"'/>";
				h += "<span><span></div><div style='float:right;display:none;'>（必选）</div></div></div>";
			}
			else{
				h += "id = '"+s.field+"Check' value='"+colTitle+"'/><div style='width: 70%;float:left;' onclick='changeState(this)' id='" + s.field + "Div'>"+colTitle + "</div>";
				h += "<div style='float:right'><span>宽度</span><input style='inline-size: 39px;height: 17px;font-size: 15px;border: 0px;margin-left: 6px;' id='" + s.field +"Width' value='"+s.width.substr(0,s.width.length -1)+"'/>";
				h += "<span><span></div></div></div>";
			}			
			colFields[j] = s.field;
			j++;
		}
	}
	$("#cusColumns").html(h);	
}
/*
 * @Description: 保存自定义列
 * @param : 
 */
$("#confirmSave").click(function(){
	var datas = "";
	for(var i = 0; i < colField.length; i++){		
		var s = $("#" + colField[i] + "Check");
		var w = $("#" + colField[i] +"Width").val();		
		datas += s.val() + "," +colField[i] + "," +s[0].checked + ",";
		if(w == ""){
			w = 0;
		}
		datas += w + "%;"; 
	}
	datas = datas.substr(0,datas.length - 1);
	$.ajax({
		url : pathUrl("tz/saveColumn.action"),
		type : "POST",
		dataType : "JSON",
		data : {
			'pageId':pageIds,
			'col' : datas
		},
		success : function(data) {
			$("#changeColumnModal").modal("hide");
			if (data.code == "0000") {
				swal_Tips_Short(data.message);
				getColumn(pageIds,initTableName);
			} else if (data.code == "9999") {
				swal_Tips(data.message);
			}
		},
		error : function(request) {
			swal_Tips_Error();
		}
	});
});
/*
 * @Description: 保存自定义列
 * @param : 
 */
$("#confirmSaves").click(function(){
	var datas = "";
	for(var i = 0; i < colFields.length; i++){		
		var s = $("#" + colFields[i] + "Check");
		var w = $("#" + colFields[i] +"Width").val();		
		datas += s.val() + "," +colFields[i] + "," +s[0].checked + ",";
		if(w == ""){
			w = 0;
		}
		datas += w + "%;"; 
	}
	datas = datas.substr(0,datas.length - 1);
	$.ajax({
		url : pathUrl("tz/saveColumn.action"),
		type : "POST",
		dataType : "JSON",
		data : {
			'pageId':"PIESS",
			'col' : datas
		},
		success : function(data) {
			$("#changeColumnModals").modal("hide");
			if (data.code == "0000") {
				swal_Tips_Short(data.message);
				getColumns("PIESS",initNewProcessTable);
			} else if (data.code == "9999") {
				swal_Tips(data.message);
			}
		},
		error : function(request) {
			swal_Tips_Error();
		}
	});
});
$("#resets").click(function(){
	var s = document.getElementsByClassName("inputCheck");
	for(var i = 0; i < s.length; i++){	
		s[i].checked = true;		
	}
	for(var i = 0; i < resetColumn.length; i++){
	 if(resetColumn[i].field != undefined){
		 var l = resetColumn[i].width;		 
		 $("#" + resetColumn[i].field + "Width").val(l.substr(0,l.length - 1));
	 }	
	}	
});

/**
 * 增加新的搜索组
 * @returns
 */
$("#addSearch").click(function(){
	if(searchCount >= 6){
		swal_Tips("搜索组数量已达上限");
		return;
	}
	var field = $("#field"+searchCount).val();
	var operator = $("#operator"+searchCount).val();
	var value = $("#value"+searchCount).val();
	if(field != "blank" && (field == "" || field == undefined || operator == "" || operator == undefined || value == "" || value == undefined)){
		swal_Tips("当前搜索组信息不完整，不能增加新的搜索组");
		return;
	}
	searchCount++;
	var searchId = "searchbox"+searchCount;
	$('#'+searchId).show();
});


/**
 * 初始化下拉框选项
 * @returns
 */
function initField(){
	for(var i = 0;i < resetColumn.length;i++){
		if(resetColumn[i].field != undefined && resetColumn[i].showSearch == undefined){
			$("#field1").append("<option value='"+resetColumn[i].field+"'>"+resetColumn[i].title+"</option>");
			$("#field2").append("<option value='"+resetColumn[i].field+"'>"+resetColumn[i].title+"</option>");
			$("#field3").append("<option value='"+resetColumn[i].field+"'>"+resetColumn[i].title+"</option>");
			$("#field4").append("<option value='"+resetColumn[i].field+"'>"+resetColumn[i].title+"</option>");
			$("#field5").append("<option value='"+resetColumn[i].field+"'>"+resetColumn[i].title+"</option>");
			$("#field6").append("<option value='"+resetColumn[i].field+"'>"+resetColumn[i].title+"</option>");
		}
	}
	$('#searchbox2').hide();
	$('#searchbox3').hide();
	$('#searchbox4').hide();
	$('#searchbox5').hide();
	$('#searchbox6').hide();
}

/**
 * 进行自定义查询
 * @returns
 */
$("#query").click(function(){
	sqlCombine = "";
	var f = executSql();
	if(f == false){
		return;
	}else{
		initTableName();
	}
});
function executSql(){
	fDisPatchFlag = null;
	fStatus = null;
	fClosed = null;
	var field1 = $("#field1").val();
	var operator1 = $("#operator1").val();
	var value1 = $("#value1").val();
	if(field1 != "blank" && (field1 == "" || field1 == undefined || operator1 == "" || operator1 == undefined || value1 == "" || value1 == undefined)){
		swal_Tips("第一搜索组信息不完整，不能进行搜索");
		return false;
	}
	if(field1 == "fDepName" || field1 == "fWorkCenter")
		field1 = "fDepId";
	if(field1 == "fStockName")
		field1 = "fStockId";
	if(field1 == "fOrderBillNo")
		fOrderBillNo =value1;
	if(field1 == "fDisPatchFlag"){
		if(value1 == 1)
			fDisPatchFlag = 1;
	}
	/*if(field1 == "fStatus"){
		if(value1 == 1)
			fStatus = 1;
		else if(value1 == 5)
			fStatus = 5;
		else
			fStatus = 3;
	}*/
	if(field1 == "fClosed"){
		if(value1 == 0){
			_fClosed = 0;
			fClosed = 0;
		}
		else if(value1 == 1){
			fClosed = 1;
			_fClosed = 1;
		}
		else
			fClosed = null;
	
	}
	value1 = value1.trim();
	if(field1 != "blank" && field1 != "fRwId" && field1 != "fDisPatchFlag" /*&& field1 != "fStatus" */ && field1 != "fClosed" /*&& field1 != "fOrderBillNo"*/
		&& field1 != "fAuxDate"	
	){
		sqlCombine = "("+"tem"+"."+field1+" "+switchOper(operator1,value1)+" )";

	}
	else if(field1 == "fAuxDate"){
		sqlCombine = "("+"UNIX"+"_"+"TIMESTAMP"+"("+"date"+"_"+"format"+"("+"tem"+"."+"fAuxDate"+","+"'%Y-%m-%d'))"+" "+switchOperr(operator1,value1)+")";
	}
	/*if(operator1 == "<>" && field1 != "fRwId" && field1 != "fDisPatchFlag" && field1 != "blank" && field1 != "fStatus" && field1 != "fClosed"){
		sqlCombine += " or ("+field1+" is NULL )" ;
	}*/
	if(field1 == "fRwId"){
		if(value1 == 1){
			sqlCombine = "(fNumber like '05.%' or fNumber like '5.%' or fNumber like '99.%')";
		}
		else{
			sqlCombine = "(fNumber not like '05.%' and fNumber not like '5.%' and fNumber not like '99.%')";
		}
	}
	for(var i = 2 ;i <= searchCount;i++){
		var index = i-1;
		var andOr = $("#andOr"+index).val();
		var field = $("#field"+i).val();
		var operator = $("#operator"+i).val();
		var value = $("#value"+i).val();
		if(field == "blank")
			continue;
		if(field != "blank" && (field == "" || field == undefined || operator == "" || operator == undefined || value == "" || value == undefined)){
			swal_Tips("第"+i+"搜索组信息不完整，不能进行搜索");
			return false;
		}
		if(field == "fDepName" || field == "fWorkCenter")
			field = "fDepId";
		if(field == "fStockName")
			field = "fStockId";
		if(field == "fDisPatchFlag"){
			if(value == 1)
				fDisPatchFlag = 1;
			continue;
		}
		/*if(field == "fStatus"){
			if(value == 1)
				fStatus = 1;
			else if(value == 5)
				fStatus = 5;
			else
				fStatus = 3;
			continue;
		}*/
		if(field == "fClosed"){
			if(value == 0){
				_fClosed = 0;
				fClosed = 0;
			}
			else if(value == 1){
				fClosed = 1;
				_fClosed = 1;
			}
			else{
				fClosed = null;
			}
			continue;
			/*if(value == 0)
				fClosed = 0;
			continue;*/
		}
	   if(field == "fOrderBillNo"){
		   fOrderBillNo =value;
			continue;
		}
		value = value.trim();
		if(sqlCombine == "" && field != "fRwId"&& field != "fAuxDate"){
			sqlCombine += " ("+"tem"+"."+field+" "+switchOper(operator,value)+" )";
		}
		else if (sqlCombine == "" && field == "fAuxDate"){
			sqlCombine += "("+"UNIX"+"_"+"TIMESTAMP"+"("+"date"+"_"+"format"+"("+"tem"+"."+"fAuxDate"+","+"'%Y-%m-%d'))"+" "+switchOperr(operator,value)+")";
		}
		else if (sqlCombine != "" && field == "fAuxDate"){
			sqlCombine += " "+andOr +" ("+"UNIX"+"_"+"TIMESTAMP"+"("+"date"+"_"+"format"+"("+"tem"+"."+"fAuxDate"+","+"'%Y-%m-%d'))"+" "+switchOperr(operator,value)+")";
		}
		else if (sqlCombine != "" && field != "fRwId"){
			sqlCombine += " "+andOr +" ("+"tem"+"."+field+" "+switchOper(operator,value)+" )";
		}
		else if(sqlCombine == "" && field == "fRwId"){
			if(value == 1){
				sqlCombine += "(fNumber like '05.%' or fNumber like '5.%' or fNumber like '99.%')"
			}
			else{
				sqlCombine += "(fNumber not like '05.%' and fNumber not like '5.%' and fNumber not like '99.%')"
			}
		}
		else{
			if(value == 1){
				sqlCombine +=  " "+andOr +"(fNumber like '05.%' or fNumber like '5.%' or fNumber like '99.%')"
			}
			else{
				sqlCombine +=  " "+andOr +"(fNumber not like '05.%' and fNumber not like '5.%' and fNumber not like '99.%')"
			}
		}
		
		/*if(operator == "<>" && field != "fRwId" && field != "blank"){
			sqlCombine += " or ("+field+" is NULL )" ;
		}*/
	}
	console.log(sqlCombine);
	for(var l = 1 ;l <= searchCount;l++){
		if(sqlCombine.indexOf("fName")!=-1){
			$("#value"+l).unbind().bind("keyup",function (event) {
				if(event.keyCode == "118"){
					IDName = event.target.id;
					jj=IDName.substring(5);
					console.log(jj);
					$("#queryName").text("查询-物料代码");
					$("#ERPModal").modal('show');
				}
				if (event.keyCode == 13) { 
					$('#query').triggerHandler('click'); 
				}
			});
			
		}else if(sqlCombine.indexOf("fNumber")!=-1){
			$("#value"+l).unbind().bind("keyup",function (event) {
				if(event.keyCode == "118"){
					IDName = event.target.id;
					jj=IDName.substring(5);
					$("#queryName").text("查询-物料代码");
					$("#ERPModal").modal('show');
				}
				if (event.keyCode == 13) { 
					$('#query').triggerHandler('click'); 
				}
			});
		}else if(sqlCombine.indexOf("fModel")!=-1){
			$("#value"+l).unbind().bind("keyup",function (event) {
				if(event.keyCode == "118"){
					IDName = event.target.id;
					jj=IDName.substring(5);
					$("#queryName").text("查询-物料代码");
					$("#ERPModal").modal('show');
				}
				if (event.keyCode == 13) { 
					$('#query').triggerHandler('click'); 
				}
			});
		}
		else{
			$("#value"+l).unbind().bind("keyup",function (event) {
				if(event.keyCode == "118"){
					IDName = event.target.id;
					jj=IDName.substring(5);
					$("#queryName").text("查询-物料代码");
					$("#ERPModal").modal('show');
				}
				if (event.keyCode == 13) { 
					$('#query').triggerHandler('click'); 
				}
			});
		}
	}
}

function switchOper(operator,value){
	var statement;
	switch(operator){
	case 'like':
		statement = "like "+"'%"+value+"%'";
		break;
	case 'left like':
		statement = "like "+"'"+value+"%'";
		break;
	case 'right like':
		statement = "like "+"'%"+value+"'";
		break;
	default:
		statement = operator+" '"+value+"'";
	}
	return statement;
}
function switchOperr(operator,value){
	var statement;
	switch(operator){
	case 'like':
		statement = "like "+"'%"+value+"%'";
		break;
	case 'left like':
		statement = "like "+"'"+value+"%'";
		break;
	case 'right like':
		statement = "like "+"'%"+value+"'";
		break;
	default:
		statement = operator+" UNIX_TIMESTAMP"+"("+"'"+value+"'"+")";
	}
	return statement;
}
/**
 * 保存检索历史
 * @returns
 */
$("#saveSearch").click(function(){
	$("#saveModal").modal('show');	
});


$("#confirms").click(function(){
	if($("#recordName").val() == null || $("#recordName").val() == ""){
		swal_Tips("请输入检索名称");
		return;
	}
	var searchStr = "";
	var field1 = $("#field1").val();
	var operator1 = $("#operator1").val();
	var value1 = $("#value1").val();
	if(field1 != "blank" && (field1 == "" || field1 == undefined || operator1 == "" || operator1 == undefined || value1 == "" || value1 == undefined)){
		swal_Tips("第一搜索组信息不完整，不能进行保存");
		return false;
		
	}
	value1 = value1.trim();
	if(field1 != "blank"){
		searchStr += "field1,"+$("#field1").val()+",operator1,"+$("#operator1").val()+",value1,"+$("#value1").val()+";";
	}
	for(var i = 2;i <= searchCount;i++){
		var index = i-1;
		var andOr = $("#andOr"+index).val();
		var field = $("#field"+i).val();
		var operator = $("#operator"+i).val();
		var value = $("#value"+i).val();
		if($("#field"+i).val() == "blank")
			continue;
		if(searchStr == ""){
			if(field != "blank" && (field == "" || field == undefined || operator == "" || operator == undefined || value == "" || value == undefined)){
				swal_Tips("第"+i+"搜索组信息不完整，不能进行保存");
				return false;
			}
			value = value.trim();
			searchStr += "field"+i+
			","+$("#field"+i).val()+",operator"+i+","+$("#operator"+i).val()+",value"+i+","+$("#value"+i).val()+";";
		}
		else{
			if(field != "blank" && (field == "" || field == undefined || operator == "" || operator == undefined || value == "" || value == undefined)){
				swal_Tips("第"+i+"搜索组信息不完整，不能进行保存");
				return false;
			}
			value = value.trim();
			searchStr += "andOr"+index+","+$("#andOr"+index).val()+",field"+i+
			","+$("#field"+i).val()+",operator"+i+","+$("#operator"+i).val()+",value"+i+","+$("#value"+i).val()+";";
		}
		
	}
	//$("#saveModal").modal('hide');
	/*$("#searchRecord").append("<option value='"+$("#recordName").val()+"'>"+$("#recordName").val()+"</option>");*/
	var data = {
			pageId:pageIds,
			searchRecord:searchStr,
			recordName:$("#recordName").val()
	};
	$.ajax({
		url : pathUrl("tz/saveSearchRecord.action"),
		type : "POST",
		async:false,
		dataType : "JSON",
		data : data,
		success : function(data) {
			if (data.code == "0000") {
				swal_Tips_Short(data.message);
				$("#saveModal").modal('hide');
				loadRecordName(pageIds,initTableName);
			} else if (data.code == "9999") {
				swal_Tips(data.message);
			}
		},
		error : function(request) {
			swal_Tips_Error();
			
		}
	});
	$("#recordName").val("");	
	
});

/**
 * 重置搜索组状态
 * @returns
 */
$("#resetSearch").click(function(){
	_fClosed=1;
	sqlCombine = '';
	resetSearchGroup();
	initTableName();	
	$('#searchRecord').val('');
	$('#recordName').val('');
});

function resetSearchGroup(){
	fDisPatchFlag = null;
	fStatus = null;
	for(var index = 1; index <= 6 ;index++){
		$("#field"+index+" option:first").prop("selected", 'selected');
		$("#operator"+index+" option:first").prop("selected", 'selected');
		$("#value"+index).val("");
		$("#valueBox"+index).html("");
		var h = "<input type='text' name='value"+index+"' id='value"+index+"' value='' class='form-control-new searchInput' autocomplete='off'>";
		$("#valueBox"+index).html(h);
		if(index < 6)
			$("#andOr"+index+" option:first").prop("selected", 'selected');
	}
	$('#searchbox2').hide();
	$('#searchbox3').hide();
	$('#searchbox4').hide();
	$('#searchbox5').hide();
	$('#searchbox6').hide();
	searchCount = 1;
}

/**
 * 根据检索历史的名字来加载历史检索记录
 * @returns
 */
function loadSearchRecord(){
	var recordName = $("#searchRecord").val();
	var data = {
			recordName:recordName,
			pageId:pageIds
	};
	if(recordName != "none")
		loadRecord(data);
}

function ifTime(index,fNumber,fName,fModel){
	$("#value"+index).val("");
	$("#valueBox"+index).html("");
	var h = "<input type='text' name='value"+index+"' id='value"+index+"' value='' class='form-control-new searchInput' autocomplete='off'>";
	$("#valueBox"+index).html(h);
	$("#operator"+index).attr("disabled",false);
	var time = {
			onClose : false,
			format : 'YYYY-MM-DD',
			isTime:false,
			donefun : function(obj) {
				// end.minDate = obj.val; // 开始日选好后，重置结束日的最小日期
				/*var attr = obj.elem.id;
				dataExport[attr] = obj.val;*/
			}
		};
	if($('#field'+index).val() == "fDate" || $('#field'+index).val() == "fStartDate" 
		|| $('#field'+index).val() == "fEndDate" || $('#field'+index).val() == "fBillDate" 
			|| $('#field'+index).val() == "fCheckDate" || $('#field'+index).val() == "fWorkDate" 
				|| $('#field'+index).val() == "fDownDate" || $('#field'+index).val() == "fPlanCommitDate" ||
				$('#field'+index).val() == "fPlanFinishDate"||$('#field'+index).val() == "fSchedulingCommitDate"
					|| $('#field'+index).val() == "fSchedulingFinishDate"|| $('#field'+index).val() == "fEndWorkDate"|| $('#field'+index).val() == "fArrivalDate"|| $('#field'+index).val() == "fAuxDate"){
		$("#valueBox"+index).html("");
		var h = "<input type='text' name='value"+index+"' id='value"+index+"' value='' class='form-control-new searchInput' autocomplete='off'>";
		$("#valueBox"+index).html(h);
		jeDate('#value'+index,time);
		$("#value"+index).unbind().bind("keyup",function (event) { 
			if (event.keyCode == 13) { 
				$('#query').triggerHandler('click'); 
			}
		})
	}
	else if($('#field'+index).val() == "fWorkShop"||$('#field'+index).val() == "fWorkShopName"){
		$("#valueBox"+index).html("");
		
		var h = "<select name = 'value"+index + "' id = 'value"+index +"' class='form-control-new' data-live-search='true' data-width='85px'></select>";
		$("#valueBox"+index).html(h);
		$.ajax({//生产车间下拉
			url : pathUrl("department/getDepNameAndId.action"),
			dataType : "JSON",
			async:false,
			success : function(data) {
				//生产车间下拉选里写值
				$("#value"+index).empty();
				for (x in data) {
					$("#value"+index).append("<option title ='"+data[x].value+"'value='"+data[x].value+"'>"+ data[x].text+"</option>");
				}
			},
			error : function(request) {
				swal_Tips_Error();
			}
		});
		
	}
	else if($('#field'+index).val() == "fDepName" || $('#field'+index).val() == "fWorkCenter"){
		$("#valueBox"+index).html("");
		
		var h = "<select name = 'value"+index + "' id = 'value"+index +"' class='form-control-new' data-live-search='true' data-width='85px'></select>";
		$("#valueBox"+index).html(h);
		$.ajax({//工作中心下拉
			url : pathUrl("workCenter/getworkCenterIdAndName.action"),
			dataType : "JSON",
			async:false,
			success : function(data) {
				//工作中心下拉选里写值
				$("#value"+index).empty();
				for (x in data) {
					$("#value"+index).append("<option title ='"+data[x].text+"'value='"+data[x].text+"'>"+data[x].value+"</option>");
				}
			},
			error : function(request) {
				swal_Tips_Error();
			}
		});
	}
	else if($('#field'+index).val() == "fStockName"){
        $("#valueBox"+index).html("");
		
		var h = "<select name = 'value"+index + "' id = 'value"+index +"' class='form-control-new' data-live-search='true' data-width='85px'></select>";
		$("#valueBox"+index).html(h);
		$.ajax({//发料仓库
			url : pathUrl("stock/getStockList.action"),
			dataType : "JSON",
			type : 'POST',
			async:false,
			success : function(data) {
				//发料仓库下拉
				$("#value"+index).empty();
				for (x in data) {
					$("#value"+index).append("<option title ='"+data[x].fStockID+"'value='"+data[x].fStockID+"'>"+data[x].fStockName+"</option>");
				}
			},
			error : function(request) {
				swal_Tips_Error();
			}
		});
	}
	else if($('#field'+index).val() == "fRwId"){
		$("#operator"+index).find("option[value='=']").attr("selected",true); 
		$("#operator"+index).attr("disabled",true);
		 $("#valueBox"+index).html("");
			
			var h = "<select name = 'value"+index + "' id = 'value"+index +"' class='form-control-new' data-live-search='true' data-width='85px'></select>";
			$("#valueBox"+index).html(h);
			$("#value"+index).append("<option title ='"+1+"'value='"+1+"'>"+"装配任务"+"</option>");
			$("#value"+index).append("<option title ='"+2+"'value='"+2+"'>"+"生产任务"+"</option>");
	}
	else if($('#field'+index).val() == "fDisPatchFlag"){
		$("#operator"+index).find("option[value='=']").attr("selected",true); 
		$("#operator"+index).attr("disabled",true);
		 $("#valueBox"+index).html("");
			
			var h = "<select name = 'value"+index + "' id = 'value"+index +"' class='form-control-new' data-live-search='true' data-width='85px'></select>";
			$("#valueBox"+index).html(h);
			$("#value"+index).append("<option title ='"+0+"'value='"+0+"'>"+"全部"+"</option>");
			$("#value"+index).append("<option title ='"+1+"'value='"+1+"'>"+"有"+"</option>");
	}
	else if($('#field'+index).val() == "fStatus" && $("#value").text() != 1){
		$("#operator"+index).find("option[value='=']").attr("selected",true); 
		$("#operator"+index).attr("disabled",true);
		 $("#valueBox"+index).html("");
			
			var h = "<select name = 'value"+index + "' id = 'value"+index +"' class='form-control-new' data-live-search='true' data-width='85px'></select>";
			$("#valueBox"+index).html(h);
			$("#value"+index).append("<option title ='"+1+"'value='"+1+"'>"+"已下达"+"</option>");
			$("#value"+index).append("<option title ='"+5+"'value='"+5+"'>"+"待下达"+"</option>");
			$("#value"+index).append("<option title ='"+3+"'value='"+3+"'>"+"已完成"+"</option>");
	}
	else if($('#field'+index).val() == "fStatus" && $("#value").text() == 1){
		$("#operator"+index).find("option[value='=']").attr("selected",true); 
		$("#operator"+index).attr("disabled",true);
		 $("#valueBox"+index).html("");
			
			var h = "<select name = 'value"+index + "' id = 'value"+index +"' class='form-control-new' data-live-search='true' data-width='85px'></select>";
			$("#valueBox"+index).html(h);
			$("#value"+index).append("<option title ='"+1+"'value='"+1+"'>"+"已下达"+"</option>");
			$("#value"+index).append("<option title ='"+3+"'value='"+3+"'>"+"已完成"+"</option>");
			$("#value"+index).append("<option title ='"+5+"'value='"+5+"'>"+"待下达"+"</option>");
	}
	else if($('#field'+index).val() == "fClosed"){
		$("#operator"+index).find("option[value='=']").attr("selected",true); 
		$("#operator"+index).attr("disabled",true);
		 $("#valueBox"+index).html("");
			
			var h = "<select name = 'value"+index + "' id = 'value"+index +"' class='form-control-new' data-live-search='true' data-width='85px'></select>";
			$("#valueBox"+index).html(h);
			$("#value"+index).append("<option title ='"+1+"'value='"+1+"'>"+"未关闭"+"</option>");
			$("#value"+index).append("<option title ='"+0+"'value='"+0+"'>"+"已关闭"+"</option>");
	}
	else if($('#field'+index).val() == "fIsOut"){
		$("#operator"+index).find("option[value='=']").attr("selected",true); 
		$("#operator"+index).attr("disabled",true);
		 $("#valueBox"+index).html("");
			
			var h = "<select name = 'value"+index + "' id = 'value"+index +"' class='form-control-new' data-live-search='true' data-width='85px'></select>";
			$("#valueBox"+index).html(h);
			$("#value"+index).append("<option title ='"+1058+"'value='"+1058+"'>"+"是"+"</option>");
			$("#value"+index).append("<option title ='"+1059+"'value='"+1059+"'>"+"否"+"</option>");
	}
	else if($('#field'+index).val() == "fNumber" || $('#field'+index).val() == "fName" 
		|| $('#field'+index).val() == "fModel"){
		$("#value"+index).unbind().bind("keyup",function (event) {
			if(event.keyCode == "118"){
				IDName = event.target.id;
				$("#queryName").text("查询-物料代码");
				jj=index;
				$("#ERPModal").modal('show');
			}
			if (event.keyCode == 13) { 
				$('#query').triggerHandler('click'); 
			}
		});
	}
	else if($('#field'+index).val() == "fWorkType"){
		$("#operator"+index).find("option[value='=']").attr("selected",true); 
		$("#operator"+index).attr("disabled",true);
		 $("#valueBox"+index).html("");
			
			var h = "<select name = 'value"+index + "' id = 'value"+index +"' class='form-control-new' data-live-search='true' data-width='85px'></select>";
			$("#valueBox"+index).html(h);
			$("#value"+index).append("<option title ='"+1+"'value='"+1+"'>"+"手动报工"+"</option>");
			$("#value"+index).append("<option title ='"+2+"'value='"+2+"'>"+"自动报工"+"</option>");
			$("#value"+index).append("<option title ='"+3+"'value='"+3+"'>"+"试车报工"+"</option>");
	}
	else{
		$("#valueBox"+index).html("");
		var h = "<input type='text' name='value"+index+"' id='value"+index+"' value='' class='form-control searchInput' autocomplete='off'>";
		$("#valueBox"+index).html(h);
		$("#value"+index).unbind().bind("keyup",function (event) { 
			if (event.keyCode == 13) { 
				$('#query').triggerHandler('click'); 
			}
		})
	}
}
function loadRecord(data){
	console.log(data.recordName);
	$('#recordName').val(data.recordName);
	$.ajax({
		url : pathUrl("tz/getSearchRecordByName.action"),
		type : "POST",
		async:false,
		dataType : "JSON",
		data : data,
		success : function(data) {
			if (data.code == "0000") {				
				resetSearchGroup();
                if(data.rows.length > 0){
                	var recordStr = data.rows.split(";");
    				for(var k = 1;k<=recordStr.length-1;k++){
    					$('#searchbox'+k).show();
    					searchCount++;
    				}
    				searchCount--;
    				for(var i=0;i<recordStr.length-1;i++){
    					if(i == 0){
    						var searchUnit = recordStr[i].split(",");
    						$("#field1").val(searchUnit[1]);
    						
    						$("#operator1").val(searchUnit[3]);
    						$("#value1").val(searchUnit[5]);
    						if(searchUnit[1] == "fWorkShop" || searchUnit[1] == "fDisPatchFlag" ||searchUnit[1] == "fDepName"
    							|| searchUnit[1] == "fStockName" ||searchUnit[1] == "fRwId" ||searchUnit[1] == "fStatus"
    								||searchUnit[1] == "fClosed"){
    							ifTime(1);
    							//$("#value1").val(searchUnit[5]);
    							$("#value1").find("option[value='"+searchUnit[5]+"']").attr("selected",true); 
    						}
    						
    					}
    					else{
    						var searchUnit = recordStr[i].split(",");
    						var index = i+1;
    						$("#andOr"+i).val(searchUnit[1]);
    						$("#field"+index).val(searchUnit[3]);
    						
    						$("#operator"+index).val(searchUnit[5]);
    						$("#value"+index).val(searchUnit[7]);
    						if(searchUnit[3] == "fWorkShop"|| searchUnit[3] == "fDisPatchFlag" ||searchUnit[3] == "fDepName"
    							|| searchUnit[3] == "fStockName" ||searchUnit[3] == "fRwId" ||searchUnit[3] == "fStatus"
    								||searchUnit[3] == "fClosed"){
    							ifTime(index);
    							//$("#value1").val(searchUnit[5]);
    							$("#value"+index).find("option[value='"+searchUnit[7]+"']").attr("selected",true); 
    						}
    					}
    				}
				}		
                else{
                	resetSearchGroup();
                	sqlCombine = "";
                }
				executSql();
				getColumn(pageIds,initTableName);
			} else if (data.code == "9999") {
				swal_Tips(data.message);
			}
		},
		error : function(request) {
			swal_Tips_Error("系统出错");
		}
	});
}

/**
 * 加载检索历史的名字
 * @returns
 */
function loadRecordName(pageId,initTables){
	pageIds = pageId;
	initTableName = initTables;
	$("#searchRecord").empty();
	$("#searchRecord").append("<option value='none'>"+"请选择"+"</option>");
	var data = {
			pageId:pageId
	};
	$.ajax({
		url : pathUrl("tz/getRecordName.action"),
		type : "POST",
		dataType : "JSON",
		data : data,
		success : function(data) {
			if (data.code == "0000") {					
				for(var i = 0;i<data.rows.length;i++){
					var s = data.rows[i];
					if(s.length > 5){
						s = data.rows[i].substr(0,5)+ "...";
					}
					$("#searchRecord").append("<option title ='"+data.rows[i]+"'value='"+data.rows[i]+"'>"+s+"</option>");
				}
				lastRecordName = data.rows[data.rows.length-1];
				$("#searchRecord").val(lastRecordName);
				var lastData = {
						recordName:lastRecordName,
						pageId:pageId
				};
				loadRecord(lastData);
			} else if (data.code == "9999") {
				swal_Tips(data.message);
			}
		},
		error : function(request) {
			swal_Tips_Error();
		}
	});
}

function deleteRecord(){
	var recordName = $("#searchRecord").val();
	if(recordName == "none" || recordName == "" || recordName == null){
		swal_Tips("请选择一条检索历史进行删除");
		return;
	}
	var data = {
			pageId:pageIds,
			recordName:recordName
	}
	showSwal(
			'删除',
			'您确定删除吗？',
			'是的，确定删除',
			function(result){
				if(result.value){
					// console.log(_cardNo,_fOperNumber,_fQty,_fSupplierID,$("#price").val(),new
					// Date(_fFetchDate.replace(/-/g, "/")));
					showLoading("删除中...");//显示正在提交中
					$.ajax({
						url : pathUrl("tz/deleteSearchRecord.action"),
						type : "POST",
						dataType : "JSON",
						data : data,
						success : function(data) {
							if (data.code == "0000") {
								swal_Tips_Short(data.message);
								loadRecordName(pageIds,initTableName);
							} else if (data.code == "9999") {
								swal_Tips(data.message);
							}
						},
						error : function(request) {
							swal_Tips_Error();
						}
					});
				}
			});	
}
/**
 * 
 * @param title
 * @param f
 * @returns
 */
function formatTitle(title,f){
	var t = title.split(f);
	var titles = '';
	for(var i = 0; i < t.length; i++){
		titles += t[i];
	}
	return titles;
}